/*公共js*/
import config from '../config.js';
var log = require('../common/log.js');

class Common {
  constructor() {
    this.imgUrl = config.imgUrl;
    this.requestApi = config.api;
    this.appId = config.appId;
    this.wx_code = config.wx_code;
    this.shopAppid = config.shopAppid;
  }
  /**
   * 异步请求
   * url:api链接
   * type:请求类型
   * data:请求参数
   * **/
  requestAjax(url, type, data) {
    let method = type || 'GET';
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.requestApi + url,
        method,
        data,
        header: {
          'token': wx.getStorageSync('token') || ''
        },
        success: (res) => {
          resolve(res);
          if (res.data.code != 1) {
            log.warn(`api:${url};data:${JSON.stringify(data)}-message:${JSON.stringify(res)}`);
          }
        },
        fail: (err) => {
          reject(err);
          log.error(`api:${url};data:${JSON.stringify(data)};message:${JSON.stringify(err)}`);
        },
        complete: () => { }
      })
    })
  }

  //记录登陆信息
  addAppData(userId, orgSeq) {
    let data = {
      "userId": userId,
      "orgSeq": orgSeq
    }
    this.requestAjax('/api/user-service/v1/authMa/addLoginRecord', 'POST', data).then(res => {
      if (res.data.code) {
        getApp().globalData.appDataid = res.data.result
      }
    })
  }

  exitAppData() {

    this.requestAjax('/api/user-service/v1/authMa/addLogoutRecord?id=' + getApp().globalData.appDataid, 'POST', {}).then(res => {
      if (res.data.code) {
        getApp().globalData.appDataid = 0;
        console.log('退出记录')
      }
    })
  }

  //检查用户登陆
  checkLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          console.log('loginerr', err)
          reject(err);
        },
        complete: (res) => { },
      })
    }).then((res) => {
      // return;
      //请求检测接口
      console.log('请求登陆检测接口');
      return this.requestAjax('/api/user-service/v1/authMa/tokenCheck', 'POST', {});
    }).then(res => {
      if (res.data.code) {
        return new Promise((resolve, reject) => {
          if (res.data.code == 1) {
            // 检测登录存储信息
            wx.setStorageSync('token', res.data.result.token);
            getApp().globalData.userId = res.data.result.userId;
            getApp().globalData.defaultShopInfo = res.data.result.orgList[0];
            getApp().globalData.orgList = res.data.result.orgList; //店铺列表
            getApp().globalData.openStatus = res.data.result.orgList[0].openStatus;
            resolve(res)
          } else {
            reject()
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '登陆状态已失效,请重新登陆!',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              wx.setStorageSync('token', '');
              wx.setStorageSync('isLogin', false)
              wx.navigateTo({
                url: '/pages/login/index',
              })
            }
          }
        })
      }

    }).catch(err => console.log(err))
  }
  /**
   * 地理位置定位
   * 
   */
  getLocalData(success, fail) {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        //关闭权限弹窗
        console.log('地理位置信息', res);
        success && success(res);
      },
      fail: err => {
        //打开地理位置权限弹窗
        console.log('拒绝定位授权');
        fail && fail();
      }
    })
  }
  //打电话
  makeCall(phone) {
    if (phone) {
      wx.showModal({
        title: '提示',
        content: '是否联系您的专属客服？',
        success: res => {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: phone
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '您还没有专属客服！',
        icon: 'none'
      })
    }
  }

  /**
   * 页面跳转 权限检查  
   * routeType 跳转方式。
   * params 参数
   * **/
  routeLink(routeUrl, params, routeType) {
    let userType = getApp().globalData.shopInfo.userType;
    //权限管理
    if (routeUrl == "/pages/rightsMgt/index") {
      routeType = 'switchTab'
      if (userType == 6) { //业务员
        routeUrl = "/pages/rightsMgt/rootEmployees/rootEmployees"
      }
    }

    let flag = true;
    routeUrl = routeUrl + params
    if (flag) {
      switch (routeType) {
        case "switchTab":
          wx.reLaunch({
            url: routeUrl,
          })
          break;
        case "redirectTo":
          wx.redirectTo({
            url: routeUrl,
          })
          break;
        case "navigateTo":
          wx.navigateTo({
            url: routeUrl,
          })
          break;
      }
    } else {
      wx.showToast({
        title: '您没有相关权限,请联系门店管理员开通!',
        icon: 'none'
      })
    }
  }
  /**
   * toast提示
   */
  showToast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    })
  }
}

export default Common